﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace Universe.WCF.Behaviors.WcfStreaming
{
    public interface IResponseStatusStorage
    {
        bool GetResponseStatus(Guid token, out ResponseStatus status);
        void StoreResponseStatus(Guid token, ResponseStatus status);
    }

    public class WebCacheResponseStatusStorage : IResponseStatusStorage
    {
        public string WorkingFolder { get; set; }
        public TimeSpan KeepAliveTime { get; set; }

        public WebCacheResponseStatusStorage()
        {
            KeepAliveTime = TimeSpan.FromMinutes(60);
        }

        public bool GetResponseStatus(Guid token, out ResponseStatus status)
        {
            var cache = HttpRuntime.Cache;
            string key = GetCacheKey(token);

            status = (ResponseStatus) cache.Get(key);
            return status != null;
        }

        private string GetCacheKey(Guid token)
        {
            return "WCFStreamResponse #" + token.ToString("N");
        }

        public void StoreResponseStatus(Guid token, ResponseStatus status)
        {
            if (status == null)
                HttpRuntime.Cache.Remove(GetCacheKey(token));

            else
                HttpRuntime.Cache.Insert(
                    GetCacheKey(token),
                    status,
                    null,
                    DateTime.Now + KeepAliveTime,
                    Cache.NoSlidingExpiration,
                    OnUpdateCallback);
        }


        static private void OnUpdateCallback(string key, CacheItemUpdateReason reason, out object o, out CacheDependency dependency, out DateTime expiration, out TimeSpan slidingExpiration)
        {
            if (reason == CacheItemUpdateReason.Expired)
            {
                // удаляем файл-буффер
                Debug.WriteLine("Expired: " + key);
            }
            else
            {
                // nothing to do: 
                // cache item has single reading behaviour
            }

            slidingExpiration = Cache.NoSlidingExpiration;
            expiration = Cache.NoAbsoluteExpiration;
            dependency = null;
            o = null;
        }

    }

}
